package com.yan.token.repository.jdbc;

import com.yan.token.module.App;
import com.yan.token.repository.AppRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Collection;

/**
 * @author yanheng
 * @data 2020/1/3 15:23
 */
@Repository
@Profile("jdbc")
public class JdbcAppRepository implements AppRepository {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public App findByAppId(String appId) {
        return jdbcTemplate.queryForObject("select id, app_id, password, token from app where app_id = ?",
                BeanPropertyRowMapper.newInstance(App.class),
                appId);
    }

    @Override
    public App findById(String id) {
        //BeanPropertyRowMapper.newInstance(App.class)
        return this.jdbcTemplate.queryForObject("select id, app_id, password, token from app where id = ?",
                (rs, rowNum) -> {
            return new App(rs.getString("id"),
                    rs.getString("app_id"),
                    rs.getString("password"),
                    rs.getString("token"));
                }, id);
    }

    @Override
    public void save(App app) {
        String insert_app = "insert into app(id, app_id, password, token) values(?, ?, ?, ?)";
        this.jdbcTemplate.update(insert_app,
                app.getId(),
                app.getAppId(),
                app.getPassword(),
                app.getToken());
    }

    @Override
    public Collection<App> findAll() {
        String sql = "select id, app_id, password, token from app";
        return this.jdbcTemplate.query(sql,
                BeanPropertyRowMapper.newInstance(App.class));

    }

    @Override
    public void deleteById(String id) {
        String sql = "delete from app where id = ?";
        this.jdbcTemplate.update(sql, id);
    }
}
